<template>
    <a-modal title="添加需求" :width="800" :bodyStyle="{ padding: '12px 24px', height: '460px' }" v-model:visible="visible">
        <div style="height: 100%; display: flex; flex-direction: column">
            <FilterForm class="ant-table-fn" @search="handleSearch" />
            <div class="ant-table-list">
                <CustomTable autoResize style="height: 100%" ref="ruleTableRef" size="small" rowKey="id" :pagination="paginationConfig" :columns="columns" :data-source="list || []" @change="handleTableChange" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
                    <template #requireType="{ record }">
                        <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
                    </template>
                    <template #level="{ record }">
                        <h-level :level="record.level" v-if="record.level" />
                    </template>
                    <template #status="{ record }">
                        <flexbox>
                            <h-status-badge :status="record.status" />
                        </flexbox>
                    </template>
                </CustomTable>
            </div>
        </div>
        <template #footer>
            <flexbox justify="flex-end" class="btn-group">
                <a-button @click="visible = false">取消</a-button>
                <a-button type="primary" :disabled="!selectedRowKeys.length" @click="handleSave">加入版本</a-button>
            </flexbox>
        </template>
    </a-modal>
</template>

<script lang="ts">
import { HLevel, HProductType, HStatusBadge } from '@/components';
import FilterForm from './FilterForm.vue';
import api from '@/api';
import store from '@/store';
import { message } from 'ant-design-vue';
import { CustomTable } from '@/components';
import { defineComponent, reactive, toRefs } from 'vue';
import { useTableRowSelect } from '@/components/Table/hooks/index';
export default defineComponent({
    components: {
        CustomTable,
        FilterForm,
        HLevel,
        HProductType,
        HStatusBadge
    },
    emits: ['success'],
    setup(_, { emit }) {
        const { selectedRowKeys, selectedRows, allSelectedRows, onSelectChange, setSelectRows } = useTableRowSelect();
        const columns = [
            {
                title: '产品需求名称',
                dataIndex: 'requireName',
                width: 200,
                ellipsis: true,
                slots: { customRender: 'requireName' }
            },
            {
                title: '需求类型',
                dataIndex: 'requireType',
                slots: { customRender: 'requireType' }
            },
            {
                title: '优先级',
                dataIndex: 'level',
                slots: { customRender: 'level' }
            },
            {
                title: '状态',
                dataIndex: 'status',
                slots: { customRender: 'status' }
            }
        ];
        const state = reactive<any>({
            visible: false,
            list: [],
            detail: {},
            searchQuery: {},
            saveQuery: {}, //保存参数
            paginationConfig: {
                total: 0,
                pageSize: 20, // 每页中显示10条数据
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '15', '20'], // 每页中显示的数据
                showTotal: (total: number) => `共有 ${total} 条数据`, // 分页中显示总的数据
                current: 1
            },
            versionSelectedRows: []
        });
        const open = (info, saveQuery = {}) => {
            state.visible = true;
            state.list = [];
            state.detail = info;
            state.saveQuery = {
                ...saveQuery
            };
            getList();
        };
        const handleSave = async () => {
            const list: any[] = [];
            const { empId, name } = store.getters.userInfo.employeeDTO;
            allSelectedRows.value.forEach((item) => {
                const { id, versionName, versionNumber } = state.detail;
                list.push({
                    productRequireId: item.id,
                    relateVersionId: id,
                    relateVersionName: versionName,
                    relateVersionNumber: versionNumber,
                    status: 'add',
                    empId,
                    empName: name,
                    ...state.saveQuery
                });
            });
            const { success, errorMsg } = await api.productRequireModel.batchDeal(list);
            if (success) {
                message.success('操作成功');
                state.visible = false;
                setSelectRows([], []);
                emit('success');
            } else {
                message.error(errorMsg);
            }
        };
        // 获取所有除去该版本下已存在的需求列表
        const getList = async () => {
            const { current, pageSize } = state.paginationConfig;
            const query = {
                requireSystem: state.detail.system,
                requireName: '',
                requireType: null,
                level: null,
                status: null,
                pageSize: pageSize,
                pageNum: current,
                ...state.searchQuery
            };
            let { success, moule, errorMsg, totalCount } = await api.productRequireModel.selectPageToVersion(query);
            if (success) {
                moule = moule || [];
                // state.list = moule.filter((item) => !item.relateVersionId);
                state.list = [...moule];
                state.paginationConfig.total = totalCount;
            } else {
                message.error(errorMsg);
            }
        };
        const handleTableChange = (val) => {
            state.paginationConfig = val;
            getList();
        };
        const handleSearch = (val) => {
            state.paginationConfig.current = 1;
            state.searchQuery = {
                ...state.searchQuery,
                ...val
            };
            getList();
        };
        return {
            ...toRefs(state),
            open,
            handleSave,
            handleSearch,
            columns,
            selectedRowKeys,
            selectedRows,
            onSelectChange,
            handleTableChange
        };
    }
});
</script>
<style lang="less" scoped>
.require-cont {
    margin-top: 8px;
    .require-item {
        height: 38px;
        width: 100%;
        padding: 0 18px;
        cursor: pointer;
        &:hover {
            background: #eaf5fe;
            border-radius: 2px;
        }
        &-title {
            margin-left: 8px;
            flex: 1;
            width: 100%;
        }
    }
}
.btn-group {
    button + button {
        margin-left: 8px;
    }
}
::v-deep(.ant-checkbox-wrapper > span:nth-child(2)) {
    width: 100%;
}
</style>